package org.bitejiuyeke;

import java.sql.*;
import java.text.MessageFormat;

/**
 * @Author 比特就业课
 */

public class Demo01_DriverManager {

    public static void main(String[] args) {

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            // 1. 加载数据库厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2. 获取数据库的连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java114?characterEncoding=utf8" +
                            "&allowPublicKeyRetrieval=true&useSSL=false",
                    "root",
                    "123456");//jdbc的方式连接mysql
            // 3. 创建Statement对象
            statement = connection.createStatement();
            // 4. 定义SQL语句
            String sql = "select id, name, sno, age, gender, enroll_date, class_id from student";
            // 5. 执行SQL语句
            resultSet = statement.executeQuery(sql);//接受查询
            // 6. 遍历结果集，获取数据行
            while (resultSet.next()) {
                // 获取ID列的值
                long id = resultSet.getLong(1);
                // 获取name列的值
                String name = resultSet.getString(2);
                String sno = resultSet.getString(3);
                int age = resultSet.getInt(4);
                byte gender = resultSet.getByte(5);
                Date enrollDate = resultSet.getDate(6);
                long classId = resultSet.getLong(7);
                System.out.println(MessageFormat.format("学生编号={0}, 姓名={1}, 学号={2}, 年龄={3}, 性别={4}, 入学时间={5}, " +
                        "班级编号={6}", id, name, sno, age, gender, enrollDate, classId));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放结果集对象
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            // 释放Statement
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            // 关闭数据库连接
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
